# -*- coding: utf-8 -*-

import time, os, urllib, json

from selenium.webdriver.common.by import By
from selenium import webdriver

from response_class import *
from qiniu import Auth, put_file, etag
from random import randint
channelShopIdList = ["wx0829c079cc4ca92a", "wx035a17f37f622fdd", "wx865aea1241c3073b", "wx9ab16ab3b9c65082"]
scan_pic_path = 'C:\\Users\\Admin\\Desktop\\'
def get_token():
    """获取七牛token"""
    token_url = "https://gw.guang.com/v4/guangApp/upload/qiniu/api/getAutomatorUploadToken?channel=igclient_public"
    text_token = RequestsEdit.getWithoutProxy(token_url)
    token = text_token.json().get("data", {}).get("token", "")
    return token

def download_img(device,img_url):
    """
    图片下载
    :param img_url:
    :return:
    """
    file_suffix = os.path.splitext(img_url)[1]
    timestamp = str(int(time.time()))
    device = device + str(randint(1, 100))
    filename = '{}{}{}'.format(device, timestamp, file_suffix)
    # 下载图片，并保存到当前文件夹中
    image_name = urllib.request.urlretrieve(img_url, filename=filename)[0]
    return image_name

def upload_img(img_name, img_path) -> str:
    '''
    img_name: 图片名
    img_path: 图片本地地址
    alias:    商品id
    type:     平台标识
    '''
    # 获取token
    token = get_token()
    # 上传后保存的文件名
    key = img_name + ".png"
    # 本地文件地址
    localfile = img_path
    # 执行上传
    try:
        ret = put_file(token, key, localfile, version='v2')
        if ret[0]:
            # 解析返回地址
            img_path = ret[0].get("data", {}).get("attachmentPath", "")
            return img_path
        else:
            return None
    except:
        print("图片上传失败")

def switch_current_page(driver):
    """切回到当前页面"""
    windows = driver.window_handles
    driver.switch_to.window(windows[-1])
    driver.implicitly_wait(5)

def save_article_info(article_dict):
    """文章数据上传"""
    url = 'http://gw.guang.com/guang-app-util/api/automator/saveArticleInfo'
    ret = RequestsEdit.post(post_data=article_dict, url=url)
    return ret

def get_article_info(article_title):
    """根据文章标题查询是否存在"""
    url = 'http://gw.guang.com/guang-app-util/api/automator/getArticleInfoByTitle'
    article_title_dict = {"articleTitle":article_title}
    ret = RequestsEdit.post_json(post_data=article_title_dict,url=url)
    return ret

def get_huxiu_article(search_term,page):
    """获取虎嗅搜索-返回值"""
    url = 'https://search-api.huxiu.com/api/article'
    tt = int(time.time())
    post_data = {
        'platform': 'www',
        's': search_term,
        'sort': '',
        'page': 1,
        'pagesize': 20,
        'appid': 'hx_search',
        # 'nonce': 'R6nGCQynH7k0LwOC',
        'timestamp': tt,
        'signature': "2cb5126dc4bb89296ca2bcf0345ec97e98f204a7"

    }
    ret = RequestsEdit.post_json(post_data=post_data,url =url)
    return ret

def is_element_exist(driver, element):
    """判断元素是否存在"""
    flag = True
    try:
        driver.find_element_by_xpath(element)
        return flag
    except:
        flag = False
        return flag

def is_element_exist_css(driver, element):
    """判断元素是否存在"""
    flag = True
    try:
        driver.find_element(By.CSS_SELECTOR, element)
        return flag
    except:
        flag = False
        return flag

"""
count 是跳转到的tab位置，从0开始计数
"""
def switch_tab(driver, count):
    handles = driver.window_handles
    driver.switch_to.window(handles[count])
    driver.implicitly_wait(5)


"""生成永久授权码"""
def save_business_auth(authCode,suiteTicket,corpId):
    url = 'https://msd.guang.com/m/wecomapp/confirm/fans-operation'
    post_data = {
    "authCode": authCode,
    "suiteTicket": suiteTicket,
    "corpId": corpId
    }
    ret = RequestsEdit.post_json(post_data=post_data,url =url)
    return ret


"""
若RPA执行时发现视频号id错误，则阻断，发送飞书消息给操作编辑的人，飞书消息格式
标题：视频号ID错误提醒
小店信息：小店名称   小店id：xxxxxx
内容：该小店添加的视频号id错误，请找达人确认并及时修改，否则会导致后续直播链路出错
"""
def send_person_msg(operator_phone, video_numberId, guang_shop_name, guang_shop_id):
    '''视频号ID异常发送消息'''
    try:
        postParam = {
                    "role": "mobile", # 机器人角色
                    "phones": [
                        operator_phone
                    ],
                    "card": {
                    "config": {
                        "wide_screen_mode": True,
                        "enable_forward": True
                    },
                    "header": {
                        "title": {
                            "content": "视频号ID(%s)错误提醒" % video_numberId,
                            "tag": "plain_text"
                        },
                        "template": "blue"
                    },
                    "elements": [
                        {
                            "tag": "markdown",
                            "content": "小店名称：%s,   小店id：%s" % (guang_shop_name, guang_shop_id)
                        },
                        {
                            "tag": "markdown",
                            "content": "该小店添加的视频号id错误，请找达人确认并及时修改，否则会导致后续直播链路出错"
                        }
                    ]
                }
            }
        print("send_person_msg:%s" % postParam)
        url = "http://gw.guang.com/guang-app-util/api/feishu/notifyToPerson"
        RequestsEdit.postWithoutProxy(postParam, url)

    except Exception as e:
        print("send_person_msg:%s" %e)


def send_group_msg(video_numberId, step_msg, result_msg):
    '''视频号ID异常发送消息'''
    try:

        postParam = {
                    "botkey": "https://open.feishu.cn/open-apis/bot/v2/hook/038d8cb5-1c72-4531-a16d-d727e446d9a5",
                    "card": {
                        "config": {
                            "wide_screen_mode": True,
                            "enable_forward": True
                        },
                        "header": {
                            "title": {
                                "content": "视频号ID/小店ID(%s)错误提醒" % video_numberId,
                                "tag": "plain_text"
                            },
                            "template": "blue"
                        },
                        "elements": [
                            {
                                "tag": "markdown",
                                "content": "出错步骤: %s" % step_msg
                            },
                            {
                                "tag": "markdown",
                                "content": "结果提示: %s" % result_msg
                            }
                        ]
                    }
            }

        url = "http://gw.guang.com/guang-app-util/api/feishu/notifyToGroup"
        RequestsEdit.postWithoutProxy(postParam, url)

    except Exception as e:
        print("send_group_msg:%s" %e)

def send_error_msg(channelShopId, step_msg, result_msg):
    '''视频号ID异常发送消息'''
    try:

        postParam = {
                    "botkey": "https://open.feishu.cn/open-apis/bot/v2/hook/038d8cb5-1c72-4531-a16d-d727e446d9a5",
                    "card": {
                        "config": {
                            "wide_screen_mode": True,
                            "enable_forward": True
                        },
                        "header": {
                            "title": {
                                "content": "步骤(%s)错误提醒" % step_msg,
                                "tag": "plain_text"
                            },
                            "template": "blue"
                        },
                        "elements": [
                            {
                                "tag": "markdown",
                                "content": "视频号小店: %s" % channelShopId
                            },
                            {
                                "tag": "markdown",
                                "content": "结果提示: %s" % result_msg
                            }

                        ]
                    }
            }

        url = "http://gw.guang.com/guang-app-util/api/feishu/notifyToGroup"
        RequestsEdit.postWithoutProxy(postParam, url)

    except Exception as e:
        print("send_group_msg:%s" %e)

def send_bind_account_result(channelShopId, videoNumberId, status, gmv=0, goodsCount=0):
    '''发送绑定关系回传结果'''
    try:
        url = 'https://msd.guang.com/client/channels/rpa/bind-account'
        post_data = {
            "gmv": gmv,
            "goodsCount": goodsCount,
            "channelShopId": channelShopId,
            "videoNumberId": videoNumberId,
            "status": status
        }
        ret = RequestsEdit.post(url=url, post_data=post_data)
        traceId = ret.headers['X-YZ-Trace']
        print(traceId)
        try:
            ret_json = ret.json()
            assert ret_json['code'] == 0
            print(ret_json)
            return ret_json
        except Exception as e:
            print("send_bind_account_result:%s; trace:%s" % (e, traceId))
    except Exception as e:
        print("send_bind_account_result:%s; trace:%s" % (e, traceId))


if __name__ == "__main__":
    print()